'use strict';

const Koa = require('koa');
const http = require('http');
const { assign } = require('lodash');
const initMiddleware = require('./middlewares');
const responseTime = require('./middlewares/responseTime')();

class Kapi {
  constructor() {
    this.app = new Koa();
    this.server = http.createServer(this.app.callback());
    this.plugins = {};
    this.config = {
      port: process.env.PORT || 3000,
      middlewares: {},
      routes: {}
    };
  }

  async start(config = {}, cb) {
    try {
      this.config = assign(this.config, config);

      await this.load();

      this.app.use(responseTime);
      this.app.use(async ctx => {
        ctx.body = 'Hello World';
      });


      this.server.listen(this.config.port, err => {
        if (err) {
          console.log(err);
          return this.stop();
        }

        if (cb && typeof cb === 'function') {
          cb();
        }
      });
    } catch (err) {
      console.log(err);
      this.stop();
    }
  }

  stop() {
    process.exit(0);
  }

  async load() {
    await initMiddleware.call(this);
  }


}

module.exports = new Kapi();
